package ads_api

import (
	"gorm.io/gorm"
	"server/global"
	"server/model/common/request"
)

type AdsApiService struct {
}

func (adsApiService *AdsApiService) CreateAdsApi(adsApi *AdsApi) (err error) {
	err = global.SysDB.Create(adsApi).Error
	return err
}

func (adsApiService *AdsApiService) DeleteAdsApi(adsApi AdsApi) (err error) {
	err = global.SysDB.Transaction(func(tx *gorm.DB) error {
		if err := tx.Model(&AdsApi{}).Where("id = ?", adsApi.ID).Update("deleted_by", adsApi.DeletedBy).Error; err != nil {
			return err
		}
		if err = tx.Delete(&adsApi).Error; err != nil {
			return err
		}
		return nil
	})
	return err
}

func (adsApiService *AdsApiService) DeleteAdsApiByIds(ids request.IdsReq, deleted_by uint) (err error) {
	err = global.SysDB.Transaction(func(tx *gorm.DB) error {
		if err := tx.Model(&AdsApi{}).Where("id in ?", ids.Ids).Update("deleted_by", deleted_by).Error; err != nil {
			return err
		}
		if err := tx.Where("id in ?", ids.Ids).Delete(&AdsApi{}).Error; err != nil {
			return err
		}
		return nil
	})
	return err
}

func (adsApiService *AdsApiService) UpdateAdsApi(adsApi AdsApi) (err error) {
	err = global.SysDB.Save(&adsApi).Error
	return err
}

func (adsApiService *AdsApiService) GetAdsApiById(id uint) (adsApi AdsApi, err error) {
	err = global.SysDB.Where("id = ?", id).First(&adsApi).Error
	return
}

func (adsApiService *AdsApiService) GetAdsApiInfoList(info AdsApiSearch) (list []AdsApi, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.SysDB.Model(&AdsApi{})
	var adsApis []AdsApi
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	err = db.Limit(limit).Offset(offset).Find(&adsApis).Error
	return adsApis, total, err
}

func (adsApiService *AdsApiService) GetAllAdsApis() (adsApi []AdsApi, err error) {
	err = global.SysDB.Find(&adsApi).Error
	return adsApi, err
}

func (adsApiService *AdsApiService) GetAdsApi() (adsApi []AdsApi, err error) {
	err = global.SysDB.Find(&adsApi).Error
	return adsApi, err
}
